# -*- coding: utf-8 -*-
from PIL import Image

def cprod(it1, it2):
    """ Cartesian product between two iterators """
    return ((a,b) for a in it1 for b in it2)

def make_tiles(im, tilesize, spacing=(0,0), border=(0,0,0,0)):
    """ Take the src img and make tiles based on spacing(vert, hor)
    and borders (left, top, right, bottom).
    """
    vspc, hspc = spacing
    bl, bt, br, bb = border

    try:
        tw, th = tilesize
    except TypeError:
        tw = th = tilesize
    # Number of horizontal tiles
    h_tiles = (im.size[0] - (bl+br)) / (tw + hspc)
    # Number of vertical tiles
    v_tiles = (im.size[1] - (bt+bb)) / (th + vspc)

    def left(tx): return bl + tx*(tw+hspc)
    def top(ty): return bt + ty*(th+vspc)
    
    tileboxes = ((left(tx), top(ty), left(tx)+tw, top(ty)+th)
                  for ty in range(v_tiles)
                  for tx in range(h_tiles))

    tiles = []
    for box in tileboxes:
        tile = im.crop(box)
        tile.load()
        tiles.append(tile)

    return tiles

def tiles_image(tiles, htiles=5, vtiles=None):
    """ Generate a new image with the given tiles """
    tw, th = tiles[0].size
    mode = tiles[0].mode
    
    if not vtiles:
        vtiles = len(tiles) / htiles
        #vtiles, r = divmod(len(tiles), htiles)
        #vtiles += 1 if r else 0
        
    im = Image.new(mode, (htiles*tw, vtiles*th))
    for (x, y) in cprod(xrange(htiles), xrange(vtiles)):
        im.paste(tiles[y*htiles + x], (x*tw, y*th))

    return im
        
